import { err, log } from '../utils/log';
import { SettingListeners } from '../utils/SettingListeners';
import Tools from '../utils/Tools';

// const webContentId = SDWebUI_ImageQuickSend.getWebContentId() || 2;
// @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
const sdAPI = window.SDWebUI_ImageQuickSend
// log('获取到当前窗口Id', webContentId);
await onLoad();//注入

export const onSettingWindowCreated = async (view: HTMLElement) => {
  // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
  const plugin_path = LiteLoader.plugins.LiteLoaderQQNT_SDWebUI_ImageQuickSend.path.plugin;
  const pages_path = `local:///${plugin_path}/pages/settings.html`;
  const css_file_path = `local:///${plugin_path}/src/style/global.css`;

  const link_element = document.createElement('link');
  link_element.rel = 'stylesheet';
  link_element.href = css_file_path;
  document.head.appendChild(link_element);

  const html_text = await (await fetch(pages_path)).text();
  view.insertAdjacentHTML('afterbegin', html_text);

  const myListener = new SettingListeners(view)
  await myListener.onLoad();
};

async function onLoad() {
  if (location.hash === '#/blank') {
    // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
    navigation.addEventListener('navigatesuccess', onHashUpdate, { once: true });
  } else {
    await onHashUpdate();
  }

  log('onLoad函数加载完成')
}

async function onHashUpdate() {
  const hash = location.hash;
  // @ts-expect-error: 该第三方库类型定义不完整，需要强制调用
  if (window.webContentId !== 2) return//尝试修复多次提醒消息的bug。只在QQ主界面注册事件。
  if (hash === '#/blank') return
  if (!(hash.includes('#/main/message') || hash.includes('#/chat'))) return;//不符合条件直接返回

  // 监听来自主进程的图像地址
  sdAPI.onNewImage(async (imagePath: string) => {
    try {
      if ((await sdAPI.getOptions()).groupList.length == 0) {
        err('未设置群组列表')
        MessageAlert.error('未设置群组列表');
        return;
      };
      ((await sdAPI.getOptions()).groupList as string[]).forEach(async (groupId: string) => {
        Tools.sendGroupImageMessage(groupId, imagePath, (await sdAPI.getOptions()).timeOut || 5);
      });
    }
    catch (error) {
      err('Failed to send image:', error);
    }
  });

  log('onHashUpdate函数加载完成')
}